<!-- 1 脚本 -->
<script lang='ts' setup name='TabContent'>
import { ref, reactive, watch } from 'vue';
import { type TabPaneName } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'


//路由表整个大对象
const router = useRouter();

//当前的路由信息
const route = useRoute();


const activeName = ref('/index')
let menuContents = ref([
    { label: '首页', name: '/index', path: "/index", closable: false ,meta:{title:'首页',icon:'user'} },
    // {label:'角色管理' , name:'/system/role',path:"/system/role"},
    // {label:'代办事项' , name:'/system/todo',path:"/system/todo"},
]);


/***
 * 切换 选项卡的时候触发路由跳转
 */
function changMenuTab(name: TabPaneName) {
    console.log('name', name)
    router.push(name as string)
}






/**
 * 删除选项卡
 */
function removeMenuTab(name: TabPaneName) {
    menuContents.value = menuContents.value.filter(item => {
        return item.name !== name
    })

    //激活最后一个
    const menuContent = menuContents.value[menuContents.value.length - 1]
    activeName.value = menuContent.name

    //切换路由
    router.push(menuContent.name)
}


/**
 * 
 * 判断当前选项卡是否存在该路径
 * @param path 
 */

function existxMenuContent(path: string) {
    let flag = false
    menuContents.value.forEach(item => {
        if (item.path === path) {
            flag = true
        }
    })

    return flag

}


//监听 route的变化 
watch(route, (newRoute) => {

    const { path, meta } = newRoute
    if (!existxMenuContent(path)) {
        menuContents.value.push({
            label: meta.title as string,
            name: path,
            path: path,
            meta:meta,
            closable: true
        })
    }


    activeName.value = path;

}, {
    immediate: true   //让进入页面 时候立即执行一次，否则 可能刷新之后 没有添加选项卡
})

</script>


<!-- 2 模板 -->
<template>


    <div class="container">
        <div class="menuTabWrapper">
            <el-tabs v-model="activeName"  @tab-change="changMenuTab" @tab-remove="removeMenuTab" class="menuTab">
                    <el-tab-pane v-for="menuContent in menuContents"  :name="menuContent.name" :closable="menuContent.closable">
                        <template #label>
                              
                             <el-icon>
                                <component :is=" menuContent.meta.icon"/>
                            </el-icon>{{ menuContent.label  }}  
                           
                        </template>
                  
                    </el-tab-pane>
            </el-tabs>
        </div>

        <!-- http://localhost/system/user -->
        <!-- http://localhost/system/todo -->
        <RouterView></RouterView>



    </div>

</template>


<!-- 3 样式 -->
<style scoped>
.container {
    padding-left: 2px;

}

 /* box-shadow: 0px 0px 50px #929192; */
.container .menuTabWrapper {
    margin-bottom: 0px;
   
}

</style>